import { defineComponent, reactive, ref, onMounted } from "vue";
import styles from "./register.module.less";
import { imgPath } from "@/common/utils";
import { useRouter } from "vue-router";
import LoginPopup from "@/components/LoginPopup/LoginPopup";
import { EyeOutlined, InfoCircleOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import validateInstance from "@/libs/validate/validate";
import { $captcha } from "@/api/captcha/captcha";
import { $register, $sendSms } from "@/api/register/register";
import { useStore as useUserStore } from "@/store/user";
import useSmsRefund from "@/hooks/useSmsRefund";
export default defineComponent({
  setup() {
    const smsRefund = useSmsRefund();
    const router = useRouter()
    const userStore = useUserStore();
    //头部
    const Header = () => (
      <div class={styles['header-box']}>
        <div class={styles.header}>
          <img class={styles.logo} src={imgPath('/logo.png')} onClick={() => { router.push('/') }} />
          <div class={styles.title}>欢迎注册</div>
        </div>
      </div>
    )

    const state = reactive({
      img: '',//图形验证图
      key: '',
      mobile: '',//手机号
      code: '',//图形验证码
      syncCode: '',//短信验证码
      syncCodeClick: false,
      password: '',//密码
      showPassword: false,
      password2: '',
      showPassword2: false,
      level: [],
      status: false,
    } as any);

    //获取图形验证码
    const requestCode = () => {
      $captcha({
        scene: 'user.register'
      }).then((res: any) => {
        state.img = res.data.img;
      })
    }
    // 执行登录
    const toLogin = () => {
      LoginPopupRef.value.open();
    }

    //获取验证码
    const getSend = () => {
      let param = {
        mobile: state.mobile,
        captcha: state.code,
        scene: undefined,
      }
      smsRefund.sendSms(param);
    }
    //密码强度验证
    const passwordIntensity = () => {
      state.level = [];
      //效验字母
      const regex = /^[A-Za-z]+$/;
      //效验符号
      const regex1 = /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]+$/;
      if (validateInstance.test(state.password, 'number')) {
        state.level.push('low')
      } else if (regex.test(state.password)) {
        state.level.push('low')
      } else if (regex1.test(state.password)) {
        state.level.push('low')
      } else if (/^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、0-9]+$/.test(state.password)) {
        state.level.push('low')
        state.level.push('middle')
      } else if (/^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、A-Za-z]+$/.test(state.password)) {
        state.level.push('low')
        state.level.push('middle')
      } else if (/^[A-Za-z0-9]+$/.test(state.password)) {
        state.level.push('low')
        state.level.push('middle')
      } else if (/^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、0-9A-Za-z]+$/.test(state.password)) {
        state.level.push('low')
        state.level.push('middle')
        state.level.push('high')
      }
    }

    const checkbox = ref(true);
    //注册
    const register = () => {
      if (!state.mobile) {
        message.error('请输入手机号')
        return;
      }
      if (!validateInstance.test(state.mobile, "phone")) {
        message.error('手机号格式错误,请重新填写');
        return;
      }
      if (!state.code) {
        message.error('请输入图形验证码');
        return;
      }
      if (!state.syncCode) {
        message.error('请输入短信验证码');
        return;
      }
      if (state.password.length < 8) {
        message.error('密码少于8位')
        return;
      }
      if (state.password2 !== state.password) {
        message.error('密码不一致');
        return;
      }
      $register({
        mobile: state.mobile,
        code: state.syncCode,
        password: state.password
      }).then((res: any) => {
        userStore.setToken(res.data?.token || '');
        userStore.setUid(res.data?.uid || '');
        message.success("注册成功");
        router.replace('/');
      })
    }

    //主体内容
    const Main = () => (
      <div class={styles['main-box']}>
        <div class={styles.main}>
          <div class={styles['main-title']}>
            <div class={styles['title-left']}>账号注册</div>
            <div class={styles['title-right']}>
              <span>已有账号？<span class={styles.login} onClick={() => { toLogin() }}>登录</span></span>
            </div>
          </div>
          <div class={styles['login-form']}>
            <div class={styles['form-row']}>
              <div class={styles['row-label']}>手机号：</div>
              <div class={styles['row-input']}>
                <input placeholder="请输入手机号" v-model={state.mobile} />
              </div>
            </div>
            <div class={styles['form-row']}>
              <div class={styles['row-label']}>图形验证码：</div>
              <div class={styles['row-input']}>
                <input placeholder="请输入图形验证码" v-model={state.code} />
              </div>
              <div class={styles['code-img']}>
                <img src={state.img} onClick={() => { requestCode() }} />
              </div>
            </div>
            <div class={styles['form-row']}>
              <div class={styles['row-label']}>短信验证码：</div>
              <div class={styles['row-input']}>
                <input placeholder="请输入短信验证码" v-model={state.syncCode} />
              </div>
              <div class={[styles['send-btn'], state.status && styles.status]} onClick={() => { getSend() }}>{smsRefund.show_text.value}</div>
            </div>
            <div class={styles['form-row']}>
              <div class={styles['row-label']}>设置密码：</div>
              <div class={styles['row-input']}>
                <input type={state.showPassword ? 'text' : 'password'} placeholder="请输入密码" v-model={state.password} onBlur={() => { passwordIntensity() }} />
                <EyeOutlined class={[styles['field-icon'], styles.hoverable]} onClick={() => { state.showPassword = !state.showPassword }} />
              </div>
            </div>
            <div class={styles.tips}>
              <InfoCircleOutlined />
              <span>密码为大于8位字母、数字和特殊符号（!@#$%^&*）三者组合</span>
            </div>
            <div class={styles['form-row']}>
              <div class={styles['row-label']}>确认密码：</div>
              <div class={styles['row-input']}>
                <input type={state.showPassword2 ? 'text' : 'password'} placeholder="请输入密码" v-model={state.password2} />
                <EyeOutlined class={[styles['field-icon'], styles.hoverable]} onClick={() => { state.showPassword2 = !state.showPassword2 }} />
              </div>
            </div>
            <div class={styles.intensity}>
              <span class={[styles.line, state.level.includes('low') && styles.low]}>弱</span>
              <span class={[styles.line, state.level.includes('middle') && styles.middle]}>中</span>
              <span class={[styles.line, state.level.includes('high') && styles.high]}>强</span>
            </div>
            <div class={styles['reg-argument']}>
              <a-checkbox style={{ marginLeft: '10px' }} v-model:checked={checkbox.value}></a-checkbox>
              <p>已阅读并同意
                <span>《中联金安会员协议》</span>
                <span>《个人信息保护政策声明》</span>
              </p>
            </div>
            <div class={styles['register-btn']} onClick={() => { register() }}>注册</div>
          </div>
        </div>
      </div>
    )

    const Footer = () => (
      <div class={styles['footer-box']}>
        <div class={styles.footer}>
          <p>
            <div class={styles.item} onClick={() => { router.push('/') }}>网站介绍</div>
            <div class={styles.item}>网站合作</div>
            <div class={styles.item} onClick={() => window.open('https://www.zljagroup.com/hzjg')}>合作机构</div>
            <div class={styles.item} onClick={() => window.open('https://www.zljagroup.com/zxns')}>联系我们</div>
            <div class={styles.item} onClick={() => { router.push('/GroupList') }}>保险相关</div>
            <div class={styles.item}>安全相关</div>
            <div class={styles.item}>索赔相关</div>
          </p>
          <p>Copyright ©中联金安保险经纪有限公司 All Rights Reserved</p>
        </div>
      </div>
    )
    const LoginPopupRef = ref(null as any);
    onMounted(() => {
      requestCode();
    })
    return () => (
      <div class={styles.register}>
        <Header />
        <Main />
        <Footer />
        <LoginPopup ref={LoginPopupRef} />
      </div>
    )
  }
})